package cn.edu.cug.cs.gtl;

import cn.edu.cug.cs.gtl.protos.Parameter;
import cn.edu.cug.cs.gtl.protos.Parameters;
import cn.edu.cug.cs.gtl.protos.TableKey;
import cn.edu.cug.cs.gtl.protos.Tuples;
import cn.edu.cug.cs.gtl.sql.executor.SQLExecutor;
import org.apache.commons.codec.digest.DigestUtils;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * 登陆界面
 * @author sunjianhao
 */
public class LoginFrame extends JFrame {
    private JTextField usernameTextField;
    private JButton loginButton;
    private JButton cancelButton;
    private JPanel showSecurityCodePanel;
    private JPanel mainPanel;
    private JButton changeSecurityCodeButton;
    private JPasswordField passwordField;
    private JTextField securityCodeTextField;

    private cn.edu.cug.cs.gtl.SecurityCodePanel securityCodePanel;

    String url="jdbc:mysql://127.0.0.1:3306/yuman?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
    String username="root";
    String password="sjh020401";
    public LoginFrame(){
        //初始化
        setContentPane(mainPanel);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
        setBounds(200,200,500,300);
        setResizable(false);
        showSecurityCodePanel.setLayout(new BorderLayout());
        securityCodePanel=new cn.edu.cug.cs.gtl.SecurityCodePanel();
        showSecurityCodePanel.add(securityCodePanel,BorderLayout.CENTER);
        //添加监听函数
        addListener();
    }

    /**
     * 添加监听函数
     */
    private void addListener() {
        //取消按钮
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        //登陆
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loginActionPerformed();
            }
        });
        //更换验证码
        changeSecurityCodeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                securityCodePanel.changeSecurityCode();
            }
        });
    }

    private void loginActionPerformed() {
        //获取输入信息
        String inputSecurityCode=securityCodeTextField.getText();
        String systemSecurityCode=securityCodePanel.getCode();
        String username=usernameTextField.getText();
        String password= String.valueOf(passwordField.getPassword());
        //密码加密
        String encryptPassword=DigestUtils.md5Hex(password);
        //防止文本框为空
        if("".equals(username))
        {
            JOptionPane.showMessageDialog(null,"用户名不能为空！");
            return;
        }
        if("".equals(password))
        {
            JOptionPane.showMessageDialog(null,"密码不能为空！");
            return;
        }
        if("".equals(inputSecurityCode))
        {
            JOptionPane.showMessageDialog(null,"验证码不能为空！");
            return;
        }
        //验证身份
        String userId = identify(username,encryptPassword);
        if(userId!=null) {
            //验证验证码输入情况
            if(inputSecurityCode.equalsIgnoreCase(systemSecurityCode)) {
                String userRoleId=getUserRoleId(userId);
                new cn.edu.cug.cs.gtl.MainFrame(userRoleId,userId);
                dispose();
            }
            else {
                JOptionPane.showMessageDialog(null,"验证码错误");
                repaint();
            }
        }
        else {
            JOptionPane.showMessageDialog(null,"登陆失败");
            usernameTextField.setText("");
            securityCodeTextField.setText("");
            passwordField.setText("");
            repaint();
        }
    }

    /**
     *获得用户角色id
     * @param id userid
     */
    private String getUserRoleId(String id) {
        try{
            TableKey tableKey = TableKey.newBuilder()
                    .setUrl(url)
                    .setUserName(username)
                    .setPassword(password)
                    .setSchemaName("yuman")
                    .setTableName("sys_user_role")
                    .build();

            //WHERE字句条件设置
            Parameters psWhere = Parameters.newBuilder()
                    .addParameter(Parameter.newBuilder().setName("user_id").setValue(id))
                    .build();

            Tuples p = SQLExecutor.select(tableKey,psWhere);
            return  p.getTuple(0).getValue(1);
        }
        catch (Exception e){
            JOptionPane.showMessageDialog(null,"查询用户角色失败");
            e.printStackTrace();
            return "-1";
        }
    }

    /**
     * 查询登陆权限
     * @param inputUsername 文本框输入的用户名
     * @param inputPassword 文本框输入的密码
     * @return 用户id
     */
String identify(String inputUsername,String inputPassword){
        try{
            TableKey tableKey = TableKey.newBuilder()
                    .setUrl(url)
                    .setUserName(username)
                    .setPassword(password)
                    .setSchemaName("yuman")
                    .setTableName("sys_user")
                    .build();


            //WHERE字句条件设置
            //设置username
            Parameters psWhere = Parameters.newBuilder()
//                    .addParameter(Parameter.newBuilder().setName("password").setValue(md5(inputPassword)))
                    .addParameter(Parameter.newBuilder().setName("user_name").setValue(inputUsername))
                    .build();

            Tuples p = SQLExecutor.select(tableKey,psWhere);
            String userId=null;
            userId=p.getTuple(0).getValue(0);
            return userId;
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public String md5(String input) {
        try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] messageDigest = md.digest(input.getBytes());
                StringBuilder hexString = new StringBuilder();
                for (byte b : messageDigest) {
                    hexString.append(String.format("%02x", b));
                }
                return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}


